﻿#pragma once

#include "ZImageControl.h"
#include "ZAnimateImageControl.h"
#include "ZContainer.h"
#include "network/ZDownloader.h"

namespace ZuiLib
{
	class ZNetControlDownloaderObserver
	{
	public:
		virtual ~ZNetControlDownloaderObserver() {}
		virtual ZRefCountedBase* GetRefPtr() = 0;
		virtual void OnFinishDownload(int errorCode, const char* path)=0;
		virtual void OnDownloadProgress(int percent)=0;
	};


	class ZNetControlDownloader:public Downloader
	{
	public:
		ZNetControlDownloader(const DownloaderHints* hints);
		static ZRefCountedPtr<ZNetControlDownloader> Instance();
		static void ReleaseInstance();

		virtual void onDataTaskSuccess(const DownloadTask& task,
			std::vector<unsigned char>& data);

		virtual void onFileTaskSuccess(const DownloadTask& task);

		virtual void onTaskProgress(const DownloadTask& task,
			int64_t bytesReceived,
			int64_t totalBytesReceived,
			int64_t totalBytesExpected);

		virtual void onTaskError(const DownloadTask& task,
			int errorCode,
			int errorCodeInternal,
			const std::string& errorStr);
	private:
		static ZRefCountedPtr<ZNetControlDownloader> s_downloader;
	};


	//网络控件，下载完成后，加载图片
	class ZNetImageControl:public ZContainer, public ZNetControlDownloaderObserver {
	public:
		ZUI_CLASS_NAME("zui.NetImageControl");

		enum State{
			STATE_UNLOAD,  //未加载
			STATE_LOADING, //加载中
			STATE_OK,			 //加载完成
			STATE_ERROR,   //加载失败
		};

		ZNetImageControl();
		~ZNetImageControl();

		virtual const char* GetClass() const;
		virtual void* GetInterface(const char* pstrName);

		virtual void PaintStatusImage(ZRenderer* hDC);
		virtual void SetAttribute(const char* pstrName, const char* pstrValue);

		//设置下载的图片的url
		void SetUrl(const char* url);
		void SetFile(const char* file);

		void SetErrorImage(const char* image);
		void SetLoadingImage(const char* image);

		//图片下载完毕
		virtual void OnFinishDownload(int errorCode, const char* path);
		virtual void OnDownloadProgress(int percent);
		virtual ZRefCountedBase* GetRefPtr() { return this; }

	private:
		void Download(const char* url);
		void LoadFile(const char* path);
		void SetState(State state);
		void UpdateState();


		ZString m_loadingImage;
		ZImageDrawInfo m_errorImage;
		SIZE m_loadMaxSize; //加载的图片尺寸

		ZString m_url;
		ZString m_file;
		State m_state;
	};


}//namespace







